package com.yz.jdd.base.activity;

import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.gyf.barlibrary.BarHide;
import com.gyf.barlibrary.ImmersionBar;
import com.trello.rxlifecycle.ActivityEvent;
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;
import com.yz.jdd.R;
import com.yz.jdd.base.event.Events;
import com.yz.jdd.base.event.RxBus;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import rx.functions.Action1;
import rx.subscriptions.CompositeSubscription;


public class BaseActivity extends RxAppCompatActivity implements IBaseView {
    protected Toast myToast;
    float scale;
    LoadingDialog loadingDialog;
    ToastDialog toastDialog;
    private int status_bar_height = 20;
    Handler toastHandler;
    protected boolean isScan = false;
    private CompositeSubscription compositeSubscription = new CompositeSubscription();
    public boolean isRefund = false;//是否是退款页面 单独设置页面样式
    public boolean finish = true;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
//        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        ImmersionBar.with(this).reset()
                .transparentStatusBar()  //透明状态栏，不写默认透明色
//                .transparentNavigationBar()  //透明导航栏，不写默认黑色(设置此方法，fullScreen()方法自动为true)
//                .transparentBar()             //透明状态栏和导航栏，不写默认状态栏为透明色，导航栏为黑色（设置此方法，fullScreen()方法自动为true）
                .statusBarColor(R.color.color_ffffff)     //状态栏颜色，不写默认透明色
//                .navigationBarColor(R.color.color_ffffff) //导航栏颜色，不写默认黑色
//                .barColor(R.color.color_ffffff)  //同时自定义状态栏和导航栏颜色，不写默认状态栏为透明色，导航栏为黑色
//                .statusBarAlpha(0.3f)  //状态栏透明度，不写默认0.0f
//                .navigationBarAlpha(0.4f)  //导航栏透明度，不写默认0.0F
//                .barAlpha(0.3f)  //状态栏和导航栏透明度，不写默认0.0f
                .statusBarDarkFont(true, 0.01f)   //状态栏字体是深色，不写默认为亮色
                .flymeOSStatusBarFontColor(R.color.color_333333)  //修改flyme OS状态栏字体颜色
//                .fullScreen(true)      //有导航栏的情况下，activity全屏显示，也就是activity最下面被导航栏覆盖，不写默认非全屏
                .hideBar(BarHide.FLAG_HIDE_BAR)  //隐藏状态栏或导航栏或两者，不写默认不隐藏
//                .addViewSupportTransformColor(toolbar)  //设置支持view变色，可以添加多个view，不指定颜色，默认和状态栏同色，还有两个重载方法
//                .titleBar(view)    //解决状态栏和布局重叠问题，任选其一
//                .statusBarView(view)  //解决状态栏和布局重叠问题，任选其一
                .fitsSystemWindows(true)    //解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色
                .supportActionBar(false) //支持ActionBar使用
//                .statusBarColorTransform(R.color.color_a5a5a5)  //状态栏变色后的颜色
//                .navigationBarColorTransform(R.color.color_a5a5a5) //导航栏变色后的颜色
//                .barColorTransform(R.color.color_a5a5a5)  //状态栏和导航栏变色后的颜色
//                .removeSupportView(toolbar)  //移除指定view支持
//                .removeSupportAllView() //移除全部view支持

                .addTag("tag")  //给以上设置的参数打标记
                .getTag("tag")  //根据tag获得沉浸式参数
//                .reset()  //重置所以沉浸式参数
                .init();

        try {
            getSupportActionBar().hide();
        } catch (Exception e) {
            e.printStackTrace();
        }

        RxBus.with(this).setEvent(Events.EVENT_302CODE)
                .setEndEvent(ActivityEvent.DESTROY).onNext(new Action1<Events<?>>() {
                    @Override
                    public void call(Events<?> events) {
                        Log.e("lkf", "EVENT_302CODE");
                        if (finish) {
                            finish();
                        }
                    }
                }).create();
    }


    private void closeAndroidPDialog() {
        try {
            Class aClass = Class.forName("android.content.pm.PackageParser$Package");
            Constructor declaredConstructor = aClass.getDeclaredConstructor(String.class);
            declaredConstructor.setAccessible(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            Class cls = Class.forName("android.app.ActivityThread");
            Method declaredMethod = cls.getDeclaredMethod("currentActivityThread");
            declaredMethod.setAccessible(true);
            Object activityThread = declaredMethod.invoke(null);
            Field mHiddenApiWarningShown = cls.getDeclaredField("mHiddenApiWarningShown");
            mHiddenApiWarningShown.setAccessible(true);
            mHiddenApiWarningShown.setBoolean(activityThread, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    public void drawFlag() {
        if (Build.VERSION.SDK_INT >= 21) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
            window.setNavigationBarColor(Color.TRANSPARENT);
        }
    }

    private void offSetStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getWindow();
                /*window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);*/
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            if (isScan) {
                return;
            }
            status_bar_height = 20;
            int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
            if (resourceId > 0) {
                status_bar_height = getResources().getDimensionPixelSize(resourceId);
            }
            View view = window.getDecorView();
            int oldPadding = view.getPaddingTop();
            view.setBackgroundResource(R.drawable.backgroud);
            view.setPadding(0, status_bar_height + oldPadding, 0, 0);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (toastHandler != null) {
            toastHandler.removeCallbacksAndMessages(null);
        }
        //subscription解绑
        if (compositeSubscription != null) {
            compositeSubscription.unsubscribe();
        }
        ImmersionBar.with(this).destroy();  //不调用该方法，如果界面bar发生改变，在不关闭app的情况下，退出此界面再进入将记忆最后一次bar改变的状态

    }

    /**
     * 显示服务器提示msg
     */
    @Override
    public void showToast(String msg) {

        if (myToast == null) {
            myToast = Toast.makeText(BaseActivity.this, msg,
                    Toast.LENGTH_SHORT);
        } else {
            myToast.setText(msg);
            myToast.setDuration(Toast.LENGTH_SHORT);
        }
        myToast.show();

    }

    /**
     * 显示服务器提示msg
     */
    @Override
    public void showToastDialog(String msg) {
        if (toastDialog != null) {
            toastDialog.dismiss();
        }

        if (toastHandler != null) {
            toastHandler.removeCallbacksAndMessages(null);
        }
        toastDialog = new ToastDialog(this, msg);
        toastDialog.show();
        toastHandler = new Handler();
        toastHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (toastDialog != null) {
                    toastDialog.dismiss();
                }

            }
        }, 3000);

    }


    /**
     * 显示loading
     */
    @Override
    public void showLoading(String msg) {
        loadingDialog = new LoadingDialog(this, msg);
        loadingDialog.show();

    }

    @Override
    public void showLoadingNoCancelable(String msg) {
        this.showLoading(msg);
        loadingDialog.setCanceledOnTouchOutside(false);
        loadingDialog.setCancelable(false);
    }


    /**
     * 隐藏loading()
     */
    @Override
    public void dismissLoading() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
    }


    @Override
    public CompositeSubscription getCompositeSubscription() {
        return compositeSubscription;
    }

    private static long lastClickTime;

    public static boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        if (0 < timeD && timeD < 1000) {

            return true;
        }
        lastClickTime = time;
        return false;

    }

    @Override
    protected void onResume() {
        closeAndroidPDialog();
        super.onResume();


    }

    @Override
    protected void onPause() {
        super.onPause();

    }
}
